const Base = require('./base.js');
const fs = require('fs');
const moment = require('moment');
const axios = require('axios');

module.exports = class extends Base {
    /**
     * 小程序授权获取用户信息
     * @returns {Promise<*>}
     */
    async UserDataAction() {
        let d = this.post();
        console.log(d);
        console.log(think.user);
        
        // const WeixinService = this.service('weixin');
        // const weixinUserInfo = await WeixinService.decryptUserInfoData(think.user.session_key, d.encryptedData, d.iv);
        // console.log(weixinUserInfo);
        // if (think.isEmpty(weixinUserInfo)) {
        //     return this.fail('授权失败,请关闭微信重新进入');
        // }
        const user = this.model('user');
        let userInfo = {
            nickname: d.nickName,
            headimgurl: d.avatarUrl,
            sex: d.gender,
            province: d.province,
            phone: d.phone,
            city: d.city,
            user_auth: 1
        };
        const users = await user.where({openid: think.user.openid}).find();
        console.log(think.uuid('v4'), 'users');
        if (think.isEmpty(users)) {
            userInfo.uuid = think.uuid('v4');
            userInfo.username = d.nickName;
            userInfo.openid = think.user.openid;
            await user.add(userInfo);
        } else {
            await user.where({openid: think.user.openid}).update(userInfo);
        }
        let userData = await user.field('id as user_id,uuid,integral,openid,nickname,headimgurl,user_auth,"T" as new_user').where({openid: think.user.openid}).find();
        userData = JSON.stringify(userData);
        userData = JSON.parse(userData);

        const TokenSerivce = this.service('token');
        const xiaoju_token = await TokenSerivce.create(userData);

        if (think.isEmpty(xiaoju_token)) {
            return this.fail('登录失败');
        }
        return this.success({xiaoju_token: xiaoju_token, userInfo: userData});
    }

    async loginAction() {
        const d = this.post();
        const user = await this.model('user').where({phone: d.phone, password: think.md5(d.password)}).find();
        if (think.isEmpty(user)) {
            return this.fail('用户名或密码错误');
        }
        const TokenSerivce = this.service('token');
        const xiaoju_token = await TokenSerivce.create({
            user_id: user.id,
            uuid: user.uuid,
            openid: think.user.openid,
        });

        if (think.isEmpty(xiaoju_token)) {
            return this.fail('登录失败');
        }
        user.login = 1;
        await this.model('user').where({id: user.id}).update({login: 1, openid: think.user.openid});
        return this.success({xiaoju_token: xiaoju_token, userInfo: user});
    }

    async logoutAction() {
        await this.model('user').where({id: think.user.user_id}).update({login: 0});
        return this.success(true);
    }

    async registeAction() {
        const d = this.post();
        console.log({openid: think.user.openid});

        const code = await think.cache('code' + d.phone);
        if (!code) return this.fail('验证码已过期，请重新获取~');
        if (d.vercode != code) return this.fail('验证码输入有误');

        await this.model('user').where({openid: think.user.openid}).update({
            phone: d.phone,
            password: think.md5(d.password),
            login: 1
        });
        console.log(222222222222);
        const user = await this.model('user').where({openid: think.user.openid}).find();
        const TokenSerivce = this.service('token');
        const xiaoju_token = await TokenSerivce.create({
            user_id: user.id,
            uuid: user.uuid,
            openid: user.openid,
        });

        return this.success({xiaoju_token: xiaoju_token, userInfo: user});
    }

    async UserDataPhoneAction() {
        let d = this.post();
        const WeixinService = this.service('weixin', 'api');
        const weixinUserInfo = await WeixinService.decryptUserInfoData(think.user.session_key, d.encryptedData, d.iv);
		console.log(think.user.session_key);
        console.log(weixinUserInfo);
        if (think.isEmpty(weixinUserInfo)) {
            return this.fail('授权失败');
        }
        const user = this.model('user');
        let userInfo = {
            phone: weixinUserInfo.phoneNumber,
            user_auth: 1
        };
        const add = await user.where({id: think.user.user_id}).update(userInfo);
        // const userData = await user.field('id as user_id,uuid,integral,openid,nickname,headimgurl,user_auth,"T" as new_user').where({id: think.user.user_id}).find();
        return this.success(weixinUserInfo.phoneNumber);
    }

    /**
     * 获取小程序二维码
     * @returns {Promise<any | void>}
     */
    async xcxCodeAction() {
        let d = this.post();
        const token = await this.service('wxapi', 'api_zb').token();
        const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${token}`;
        const response = await axios.post(url, {
            page: d.page,
            scene: d.scene
        }, {responseType: 'stream'});
        let img_url = 'XIAOJU' + moment().format('YYYYMMDDHHmmss') + '' + Math.random().toString().substr(3, 6) + '.png';
        response.data.pipe(fs.createWriteStream(`c:/static/code/${img_url}`));
        return this.success(think.config('xcx.upload_domain') + 'code/' + img_url);
    }

    /**
     * 用户地址
     * @returns {Promise<void>}
     */
    async addressAction() {
        const result = await this.model('address').where({
            user_id: think.user.user_id,
            status: 0
        }).order('is_default DESC,update_time DESC').select();
        return this.success(result);
    }

    async addressOrderAction() {
        const result = await this.model('address').where({
            user_id: this.post('user_id'),
            status: 0
        }).order('is_default DESC,update_time DESC').select();
        return this.success(result);
    }

    /**
     * 地址添加修改
     * @returns {Promise<void>}
     */
    async addressEditAction() {
        const d = this.post();
        const result = await this.model('address').thenUpdate({
            user_id: think.user.user_id,
            username: d.username,
            area: d.area,
            address: d.address,
            phone: d.phone,
            is_default: d.is_default,
            update_time: moment().format('YYYY-MM-DD HH:mm:ss')
        }, {id: d.address_id});
        if (d.is_default === 1) {
            const update_default = await this.model('address').where({
                user_id: think.user.user_id,
                id: ['!=', result],
                is_default: 1
            }).update({is_default: 0});
        }
        return this.success('添加成功');
    }

    /**
     * 地址删除
     * @returns {Promise<void>}
     */
    async addressDelAction() {
        const result = await this.model('address').where({
            user_id: think.user.user_id,
            id: this.post('address_id')
        }).update({status: -1});
        return this.success('删除成功');
    }

    /**
     * 地址默认设置
     * @returns {Promise<void>}
     */
    async addressDefaultAction() {
        const address_id = this.post('address_id');
        const update_default = await this.model('address').where({
            user_id: think.user.user_id,
            id: address_id,
        }).update({is_default: 1});
        const update_default_other = await this.model('address').where({
            user_id: think.user.user_id,
            id: ['!=', address_id],
            is_default: 1
        }).update({is_default: 0});

        const result = await this.model('address').where({
            user_id: think.user.user_id,
            status: 0
        }).order('is_default DESC,update_time DESC').select();
        return this.success(result);
    }

    /**
     * 客户预约上面量衣
     * @returns {Promise<void>}
     */
    async appointmentAction() {
        const d = this.post();
        const result = await this.model('appointment').add({
            user_id: think.user.user_id,
            appoint_time: d.appoint_time || '',
            username: d.username,
            pro_id: d.pro_id || 0,
            appoint_no: moment().format('YYYYMMDDHHmmss') + Math.random().toString().substr(2, 6),
            phone: d.phone,
            area: d.area,
            address: d.address,
            province: d.province,
            city: d.city,
            parter_id: 0,
            update_time: moment().format('YYYY-MM-DD HH:mm:ss')
        });
        return this.success('预约成功');
    }

    /**
     * 预约记录
     * @returns {Promise<void>}
     */
    async appoint_recordAction() {
        const d = this.post();
        const result = await this.model('appointment').where({
            user_id: think.user.user_id, status: ['>', -1]
        }).page(d.page || 1, d.limit || 30).order('add_time desc').countSelect();
        return this.success(result);
    }

    /**
     * 客户预约数
     * @returns {Promise<void>}
     */
    async appointmentCountAction() {
        const result = await this.model('appointment').count();
        return this.success(result);
    }

    async linkAction() {
        const result = await this.model('link').where({
            linktype: this.post('linktype'),
            visible: 1
        }).order('linkorder').select();
        return this.success(result);
    }

    async sizecodeAction() {
        const d = this.post();
        let res = await this.model('custom_sizecode').setRelation('category').where({
            memberid: think.user.user_id,
            classid: d.class_id
        }).order('updatetime').limit(2).select();
        let show = 0;
        for (let i = 0; i < res.length; i++) {
            const m = moment().diff(res[i].updatetime, 'month');
            console.log(m)
            if (m >= 3) {
                show = 1;
            }
            res[i].updatetime=moment(res[i].updatetime).format('YYYY-MM-DD')
            res[i].time=moment(res[i].updatetime).format('YYYY年M月D日')
        }
        return this.success({show: show, list: res});
    }

    /**
     * 获取登录验证码
     * @returns {Promise<*>}
     */
    async phone_codeAction() {
        let d = this.post();
        const code = Math.random().toString().substr(2, 4);
        think.cache('code' + d.phone, code, {timeout: 120 * 1000});
        const sms = await this.service('sms').send({
            phone: d.phone, code: code
        });
        console.log(sms);
        if (sms.statusCode !== 200) {
            return this.fail(sms.message);
        }
        return this.success(true);
    }
};
